package com.haitaoit.chengquan.module.center.activity.info;

import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.center.model.ProvinceBase;
import com.haitaoit.chengquan.module.center.model.area;
import com.haitaoit.chengquan.module.center.model.city;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.utils.Utils;
import com.haitaoit.chengquan.view.pickerview.OptionsPopupWindow;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class MyAddressAddActivity extends BaseActivity {
    @ViewInject(R.id.address_lixiren)
    EditText address_lixiren;
    @ViewInject(R.id.address_phone)
    EditText address_phone;
    @ViewInject(R.id.add_detail)
    EditText add_detail;
    @ViewInject(R.id.add_ssqtv)
    TextView add_ssqtv;

    private List<ProvinceBase> province;
    private List<city> city;
    private List<area> region;

    private ArrayList<String> options1Items = new ArrayList<String>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<ArrayList<String>>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<ArrayList<ArrayList<String>>>();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_my_address_add);
        setTitle_V("添加地址");
        setLeftShow(1, R.mipmap.left);
        setRightShow(0, R.string.save);
        backLeft_V();
        ViewUtils.inject(this);

    }

    @OnClick({R.id.right, R.id.add_ssqLL, R.id.address_add_LL,})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right:// 保存
                if (address_lixiren.getText().toString().equals("")) {
                    ToastUtils.showToast("请输入联系人！");
                } else if (!Utils.isMobileNum(address_phone.getText().toString())) {
                    ToastUtils.showToast("手机号格式有误请重新输入！");
                } else if (add_ssqtv.getText().toString().equals("")) {
                    ToastUtils.showToast("请选择省市区！");
                } else if (add_detail.getText().toString().equals("")) {
                    ToastUtils.showToast("请输入详细地址！");
                } else {
                    httpGetupdate_user_address();
                }
                break;
            case R.id.add_ssqLL:// 省市区
                // 收起键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(MyAddressAddActivity.this.getCurrentFocus().getWindowToken(), 0);

                options1Items = new ArrayList<String>();
                options2Items = new ArrayList<ArrayList<String>>();
                options3Items = new ArrayList<ArrayList<ArrayList<String>>>();
                InputStream inputStream = getResources().openRawResource(R.raw.region);
                province(inputStream);
                // 地址选择器
                OptionsPopupWindow pwOptions = new OptionsPopupWindow(this, "选择地区");
                // 三级联动效果
                pwOptions.setPicker(options1Items, options2Items, options3Items, true);
                // 设置默认选中的三级项目
                pwOptions.setSelectOptions(0, 0, 0);
                // 监听确定选择按钮
                pwOptions.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3) {
                        // 返回的分别是三个级别的选中位置
                        String tx = options1Items.get(options1) + ","
                                + options2Items.get(options1).get(option2) + ","
                                + options3Items.get(options1).get(option2).get(options3);
                        add_ssqtv.setText(tx);
                    }
                });
                pwOptions.showAtLocation(LayoutInflater.from(this).inflate(R.layout.activity_my_address_add, null),
                        Gravity.BOTTOM, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                break;
            case R.id.address_add_LL:// 设为默认地址
                break;
        }
        super.onClick(v);
    }

    private void httpGetupdate_user_address() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("address_id", "0"));
        list.add(new NameValuePairSign("name", address_lixiren.getText().toString()));
        list.add(new NameValuePairSign("phone", address_phone.getText().toString()));
        list.add(new NameValuePairSign("area", add_ssqtv.getText().toString()));
        list.add(new NameValuePairSign("address", add_detail.getText().toString()));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("address_id", "0");
        params.addQueryStringParameter("name", address_lixiren.getText().toString());
        params.addQueryStringParameter("phone", address_phone.getText().toString());
        params.addQueryStringParameter("area", add_ssqtv.getText().toString());
        params.addQueryStringParameter("address", add_detail.getText().toString());
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getupdate_user_address, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {

                String jsonString = arg0.result.toString();
                Log.d("tag", "jsonString:"+jsonString);
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            setResult(1);
                            finish();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * @param inputStream
     * @tab 解析从本地获取的json
     */
    private void province(InputStream inputStream) {
        String a = getString(inputStream);
        try {
            JSONObject jsondata = new JSONObject(a);
            Gson gson = new Gson();
            province = gson.fromJson(jsondata.getString("data"),
                    new TypeToken<List<ProvinceBase>>() {
                    }.getType());
//            Log.e("tag", province.toString());
            ArrayList<String> options2Items_i = null;
            ArrayList<ArrayList<String>> options3Items_j = null;
            for (int i = 0; i < province.size(); i++) {
                options1Items.add(province.get(i).getName());
                city = province.get(i).getCity();
                options2Items_i = new ArrayList<String>();
                options3Items_j = new ArrayList<ArrayList<String>>();
                for (int j = 0; j < city.size(); j++) {
                    options2Items_i.add(city.get(j).getName());
                    region = city.get(j).getArea();
                    ArrayList<String> options3Items_j_j2 = new ArrayList<String>();
                    for (int j2 = 0; j2 < region.size(); j2++) {
                        options3Items_j_j2.add(region.get(j2).getName());
                    }
                    options3Items_j.add(options3Items_j_j2);
                }
                options2Items.add(options2Items_i);
                options3Items.add(options3Items_j);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static String getString(InputStream inputStream) {
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer sb = new StringBuffer("");
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}
